<!--
 * @description  : 案件-简易案件-当场处罚程序检查笔录文书
 * @descriptionDetail: 案件-简易案件-当场处罚程序检查笔录文书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-25 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" :title="navTitle">
      <view class="theme-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="top-title-content">
      <view class="main-title">
        {{ localCheckForm.orgShortName }}
      </view>
      <view class="sub-title">
        现场检查（勘验）笔录
      </view>
    </view>
    <u-gap height="20" bg-color="#f2f2f2"></u-gap>
    <view class="main-content">
      <u-form :model="localCheckForm" :error-type="errorType" :rules="rules" class="form-content" ref="uForm">
        <u-form-item
          :required="isRequired"
          label="检查（勘验）开始时间"
          :label-position="labelPosition"
          right-icon="arrow-right"
          prop="checkTimeS"
          ref="startChangeRef"
        >
          <u-input
            placeholder="请选择日期"
            :disabled="true"
            v-model="localCheckForm.checkTimeS"
            @click="clicDatekHandle('isShowCyBegin')"
          />
        </u-form-item>
        <u-form-item
          :required="isRequired"
          label="检查（勘验）结束时间"
          :label-position="labelPosition"
          right-icon="arrow-right"
          prop="checkTimeE"
          ref="endChangeRef"
        >
          <u-input
            placeholder="请选择日期"
            :disabled="true"
            v-model="localCheckForm.checkTimeE"
            @click="clicDatekHandle('isShowCyEnd')"
          />
        </u-form-item>
        <u-form-item
          label="检查（勘验）地点"
          :label-position="labelPosition"
          :required="isRequired"
          prop="checkAddress"
        >
          <u-input
            placeholder="请填写检查（勘验）地点"
            :disabled="!state.canEdit"
            v-model="localCheckForm.checkAddress"
          />
        </u-form-item>
        <u-form-item label="被检查人" :label-position="labelPosition" :required="isRequired" prop="locPic">
          <u-input placeholder="请输入被检查人" :disabled="!state.canEdit" v-model="localCheckForm.locPic" />
        </u-form-item>
        <u-form-item label="性别" :label-width="labelWidth">
          <dic-input
            :keyWord="$u.dic.DIC_KEYS.C_GENDER_LIST"
            :dicCode="localCheckForm.locPicSex"
            :border="border"
            type="select"
            :select-open="dicSelectOpen($u.dic.DIC_KEYS.C_GENDER_LIST)"
            placeholder="请选择"
            :disabled="!state.canEdit"
            v-model="localCheckForm.sexName"
            @changeInputModelData="(name)=>{$set(localCheckForm, 'sexName', name)}"
            @click="showDic($u.dic.DIC_KEYS.C_GENDER_LIST,localCheckForm.locPicSex,)"
          />
        </u-form-item>
        <u-form-item label="年龄" :label-width="labelWidth">
          <u-input
            placeholder="请输入年龄"
            type="number"
            :disabled="!state.canEdit"
            v-model="localCheckForm.age"
          />
        </u-form-item>
        <u-form-item label="联系电话" :label-position="labelPosition" prop="connectPhone">
          <u-input placeholder="请输入联系电话" :disabled="!state.canEdit" v-model="localCheckForm.connectPhone" />
        </u-form-item>
        <u-form-item label="零售许可证核定经营地址" :label-position="labelPosition">
          <u-input
            placeholder="请输入零售许可证核定经营地址"
            :disabled="!state.canEdit"
            v-model="localCheckForm.licNoBusiAddr"
          />
        </u-form-item>
        <u-form-item label="零售许可证号" :label-position="labelPosition">
          <u-input placeholder="请输入零售许可证号" :disabled="!state.canEdit" v-model="localCheckForm.licenseNo" />
        </u-form-item>
        <u-form-item :border-bottom="false" label-width="auto" label="检查笔录" label-position="left">
          <u-icon
            slot="right"
            customPrefix="csbi-icon"
            name="moban"
            size="40"
            :color="$theme.u_type_primary"
            @click="tapFieldPress('talkItem')"
          ></u-icon>
        </u-form-item>
        <u-form-item label="" label-position="top">
          <view>
            <view>
              <u-input
                type="textarea"
                height="35"
                :auto-height="true"
                :disabled="!state.canEdit"
                :maxlength="maxLength"
                v-model="localCheckForm.talkItem"
              />
            </view>
            <view class="check-content">
              <u-checkbox-group :wrap="true" :label-disabled="true" :disabled="!state.canEdit">
                <u-checkbox
                  :name="item.value"
                  v-for="(item, index) in checkRecordList"
                  :key="index"
                  v-model="item.checked"
                  @change="checkboxChange"
                >
                  <view>
                    {{ item.name }}
                  </view>
                  <!-- 可填写内容 -->
                  <u-input
                    placeholder="请输入"
                    class="input-text"
                    style="width: 150px;"
                    :disabled="true"
                    v-if="index==0"
                    v-model="localCheckForm.licenseNo"
                  />
                  <view class="" v-if="index==1">
                    <u-input
                      placeholder="请输入"
                      class="input-text"
                      style="width: 150px;"
                      :disabled="!state.canEdit?!state.canEdit:!isDisPurchase"
                      v-model="localCheckForm.purchaseLocation"
                    />
                    购进存放在经营场所用于销售，
                  </view>
                </u-checkbox>
              </u-checkbox-group>
            </view>
            <view class="check-content">
              查获时，被检查人
              <u-radio-group
                :disabled="!state.canEdit"
                v-model="localCheckForm.isIn"
                @change="radioGroupChange"
              >
                <u-radio :name="item.value" v-for="item in ISEXIT" :key="item.key">
                  {{ item.name }}
                </u-radio>
              </u-radio-group>案发现场。
            </view>
            <view class="check-content">
              执法人员依法履行检查职责，未对当事人人身、财产造成损失。
            </view>
            <view class="check-content">
              执法人员依法告知当事人享有陈述权和申辩权。
            </view>
          </view>
        </u-form-item>
        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-title">
                检查（勘验）人
              </view>
              <view class="uicon-sty" @click="()=>{if(state.canEdit) addPerson()}">
                <u-icon name="plus-circle" color="#2979ff" size="40"></u-icon>
              </view>
            </view>
            <u-input placeholder="请输入" :disabled="true" v-model="localCheckForm.undertaker" />
          </view>
        </u-form-item>

        <u-form-item label-width="200" label="当事人签名" label-position="left" prop="fileId">
          <view
            style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;"
            @click="showSignView"
          >
            <m-upload
              :uploadParam="{'fiGroupCode':'zmglpt-regie-zj-images'}"
              maxCount="1"
              :file-list="signImgList"
              uploadText="未签名"
              :showDefView="false"
              :deletable="state.canEdit"
              width="300rpx"
              height="150rpx"
              index="signImgList"
              :disabled="true"
              imageMode="aspectFit"
              @on-list-change="changeUpload"
            >
            </m-upload>
          </view>
          <signature :mustHor="true" :visible="isShowSignView" :disabled="!state.canEdit" @close="isShowSignView = false" @save="saveSign">
          </signature>
        </u-form-item>

        <u-form-item :border-bottom="false">
          <view class="" style="width: 100%;">
            <view class="" v-show="goodsListShow">
              <u-table font-size="26">
                <u-tr class="u-tr">
                  <u-th width="12%" class="u-th">
                    序号
                  </u-th>
                  <u-th class="u-th" width="48%">
                    品种规格
                  </u-th>
                  <u-th class="u-th" width="22%">
                    数量(条)
                  </u-th>
                  <u-th class="u-th" width="18%">
                    单位
                  </u-th>
                </u-tr>
                <u-tr
                  class="u-tr"
                  v-for="(item,index) in localCheckForm.goodsDtlNewList"
                  :key="item.goodsUuid"
                >
                  <u-td width="12%" class="u-td">
                    {{ index+1 }}
                  </u-td>
                  <u-td class="u-td" width="48%">
                    {{ item.goodsName }}
                  </u-td>
                  <u-td class="u-td" width="22%">
                    {{ item.qty }}
                  </u-td>
                  <u-td class="u-td" width="18%">
                    {{ item.unit }}
                  </u-td>
                </u-tr>
              </u-table>
            </view>
          </view>
        </u-form-item>
      </u-form>

      <!-- 底部按钮开始 -->
      <view class="bottom-btn-info" v-if="state.canEdit">
        <u-row gutter="16">
          <u-col span="6">
            <u-button plain type="primary" @click="submitBtn('save')">
              保存
            </u-button>
          </u-col>
          <u-col span="6">
            <u-button type="primary" @click="submitBtn('submit')">
              提交
            </u-button>
          </u-col>
        </u-row>
      </view>
      <!-- 底部按钮结束 -->
      <dic-choice
        :keyWord="dicKeyWords"
        :currentSelect="dicCurrentSelect"
        v-model="dicShow"
        @confirm="selectDicConfirm"
      ></dic-choice>
      <!-- 人员选择 -->
      <u-popup mode="bottom" height="80%" v-model="personSelectShow">
        <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
      </u-popup>
      <u-picker
        mode="time"
        :params="paramsDate"
        v-model="isShowCyBegin"
        @confirm="changeDate('checkTimeS',$event)"
      ></u-picker>
      <u-picker mode="time" :params="paramsDate" v-model="isShowCyEnd" @confirm="changeDate('checkTimeE',$event)">
      </u-picker>
      <u-popup mode="bottom" height="80%" v-model="showFieldTpl">
        <doc-form-content-tep
          :params="fieldParam"
          formName="localCheckForm"
          :fieldkey="fieldKey"
          @choice="choiceFieldTpl"
        ></doc-form-content-tep>
      </u-popup>
    </view>
  </view>
</template>

<script>
	import caseCommon from "../caseCommonMixin.js";
	import officeService from "@/service/case/office.service.js";
	import PersonSelection from "@/pages/case/components/personSelection.vue";
	import DicChoice from "@/components/dic_choice.vue";
	import DicInput from "@/components/dic_input.vue";
	import DocFormContentTep from "../components/docFormContentTemplate.vue";
	import zjCommonService from "@/service/common/common.service";
	import Signature from "@/components/signature";
	import mUpload from '@/components/m-upload.vue';
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			"dic-choice": DicChoice,
			"dic-input": DicInput,
			PersonSelection,
			DocFormContentTep,
			Signature,
			mUpload,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				paramsDate: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false,
					timestamp: true,
				},
				ISEXIT: [{
						name: "在",
						value: "1",
						key: "exit",
					},
					{
						name: "不在",
						value: "0",
						key: "noExit",
					},
				],
				checkRecordList: [{
					name: '有烟草专卖零售许可证，证件号码：',
					value: '1',
					checked: false,
					disabled: false,
				}, {
					name: '无烟草专卖零售许可证，上述卷烟系当事人从',
					value: '2',
					checked: false,
					disabled: false,
				}, {
					name: '当事人无法向本局执法人员提供卷烟在当地批发企业购进的合法有效证明；',
					value: '3',
					checked: false,
					disabled: false,
				}, {
					name: '当事人未在核定地点亮证经营。',
					value: '4',
					checked: false,
					disabled: false,
				}, ],
				dicShow: false, // dic_select 是否显示
				dicKeyWords: "", // dic 关键字
				dicCurrentSelect: "", // dic 当前选择项
				border: false,
				mode: 'date',
				maxDate: '2099-12-31',
				isShowCyBegin: false,
				isShowCyEnd: false,
				isDisPurchase: false,
				errorType: ['border-bottom', 'message', ],
				isRequired: true,
				labelWidth: '220',
				labelPosition: 'top',
				maxLength: 9999,
				isCanClick: false, // 是否可点击承办人按钮
				employeeLst: [], // 选择人员数据
				caseParam: {}, // 上个页面传过来的参数
				localCheckForm: {},
				doc: {},
				personSelectShow: false,
				psParam: {
					min: 2,
				},
				rules: {
					checkTimeS: [{
						required: true,
						message: '请选择检查（勘验）开始日期',
						trigger: ['change', 'blur', ],
					}, ],
					checkTimeE: [{
							required: true,
							message: '请选择检查（勘验）结束日期',
							trigger: ['change', 'blur', ],
						},
						{
							validator: (rule, value, callback) => {
								return this.localCheckForm['checkTimeE'] < this.localCheckForm['checkTimeS'] ?
									false : true;
							},
							message: '结束日期必须大于开始日期',
						},
					],
					checkAddress: [{
						required: true,
						message: '请输入检查（勘验）地点',
						trigger: ['change', 'blur', ],
					}, ],
					locPic: [{
						required: true,
						message: '请输入被检查人',
						trigger: ['change', 'blur', ],
					}, ],
					connectPhone: [{
						validator: () => {
							if (this.localCheckForm.connectPhone) {
								return this.$u.test.mobile(this.localCheckForm.connectPhone);
							} else {
								return true;
							}
						},
						message: '联系电话不正确',
						trigger: ['change', 'blur', ],
					}, ],
					byCheckAdvice: [{
						required: true,
						message: '请输入被检查（勘验）人或现场负责人意见',
						trigger: ['change', 'blur', ],
					}, ],
				},
				goodsListShow: true,
				titSty: {
					'font-size': '32rpx',
					'padding-left': '0rpx',
				},
				record2: '2',
				saveData: {},
				isShowSignView: false,
				signImgList: [],
				btnType: "",
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},
		computed: {},
		watch: {
			isShowCyBegin(newValue, oldValue) {
				this.$refs.startChangeRef.validation();
			},
			isShowCyEnd(newValue, oldValue) {
				this.$refs.endChangeRef.validation();
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo ? docInfo : {};
				this.setRightBtns();
			});
			console.log(this.checkRecordList)
			this.initDocData();

		},
		methods: {
			initDocData() {
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						this.docFields = [...docConfigs.data, ];
						let parms = {
							id: this.caseParam.id,
							docUuid: this.caseParam.docUuid,
							bizUuid: this.caseParam.bizUuid,
						}
						this.$modal.showLoading('加载中');
						// 获取数据
						officeService.getLocalCheck(parms).then((res) => {
							this.$modal.hideLoading();
							let [tiInfo, rs, ] = [{}, {}, ];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
							} else {
								rs = res.data[0];
							}
							// 回显检查笔录
							if (rs.choiceBox) {
								this.checkRecordList.forEach(item => {
									item['checked'] = rs.choiceBox.includes(item.value);
								});
								this.isDisPurchase = rs.choiceBox.includes(this.record2);
							}

							this.localCheckForm = rs;
							if (!this.$u.test.isEmpty(this.localCheckForm.fileId)) {
								this.signImgList = [{
									gfiId: this.localCheckForm.fileId,
								}, ];
							}
						});
					}
				});

			},
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			saveSign(v) {
				console.log(v);
				this.isShowSignView = false;
				this.$modal.showLoading('保存签名...');
				let uploadParam = {
					'fiGroupCode': 'zmglpt-regie-zj-images',
				};
				uploadParam.fileName = Date.now() + '.jpg';
				zjCommonService.uploadBase64ForApp(v, uploadParam).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						this.signImgList = [res.bean, ]
						this.localCheckForm.fileId = res.bean.gfiId;
					} else {
						console.log(res.msg);
						this.$u.toast('签名信息保存失败');
					}
				}).catch(er => {
					console.log(er);
					this.$modal.hideLoading();
					this.$u.toast('签名信息保存失败');
				});
			},
			// 上传/删除图片事件
			changeUpload(list, key) {
				if (key == 'signImgList') {
					if (list.length == 0) {
						this.localCheckForm.fileId = "";
						this.signImgList = []
					}
					return;
				}
			},
			showSignView() {
				if (!this.state.canEdit) return;
				this.isShowSignView = true;
			},
			dicSelectOpen: function(keyWords) {
				if (this.dicKeyWords == keyWords && this.dicShow) {
					return true;
				}
				return false;
			},
			showDic: function(key, cur) {
				if (!this.state.canEdit) return;
				if (this.dicShow) return;
				this.dicKeyWords = key;
				this.dicCurrentSelect = cur;
				this.dicShow = true;
			},
			selectDicConfirm: function(e) {
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.C_GENDER_LIST) {
					this.localCheckForm.sexName = e[0].label;
					this.localCheckForm.locPicSex = e[0].extra.bcbCode;
				}
			},
			clicDatekHandle(type) {
				if (!this.state.canEdit) return;
				this[type] = true;
			},
			changeDate(type, e) {
				this.localCheckForm[type] = this.$u.date(e.timestamp, 'yyyy年mm月dd日 hh时MM分')
			},
			radioGroupChange(e) {
				this.localCheckForm.isIn = e;
			},
			checkboxChange(e) {
				if (e.name == this.record2) {
					this.isDisPurchase = e.value;
					!e.value && (this.localCheckForm.purchaseLocation = '');
				}
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.submitBtn('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			// 点击提交、保存按钮
			submitBtn(type) {
				if (type == 'preview') {
					if (!this.doc.isRecorded) {
						this.$u.toast('请先保存数据');
						return;
					}
					officeService.buildLocalPunish("/punish/doc-local-check-record", this.doc.docInsUuid).then(pdfId => {
						if (pdfId.success) {
							this.downloadFile(pdfId.bean, "预览", false);
						} else {
							this.$u.toast(pdfId.msg);
						}
					});
				} else {
					let flag = this.validForm(type);
					if (flag) {
						this.submitDocInfo(type);
					}
				}
			},
			// 保存/提交接口
			submitDocInfo(flag) {
				let [docGoodsReg, self, selIds, ] = [this.localCheckForm, this, [], ];
				let {
					titemUuid,
					docUuid,
					id,
					type,
					bizUuid,
					caseCode,
					caseType,
				} = this.caseParam;
				// 检查笔录
				this.checkRecordList.filter(item => item.checked).map(item => {
					selIds.push(item.value);
				});
				docGoodsReg['choiceBox'] = selIds.length > 0 && (selIds.join(','));
				docGoodsReg['caseUuid'] = this.caseParam.caseUuid;
				docGoodsReg['licNo'] = docGoodsReg.licenseNo;
				flag == 'save' && this.$u.loading('数据保存中...');
				officeService.saveLocalCheck(docGoodsReg, docUuid, titemUuid, id, type).then((res) => {
					this.$u.hideLoading();
					if (res.success) {
						this.$u.toast(res.msg);
						let bean = res.bean;
						docGoodsReg.checkRecordUuid = bean.checkRecordUuid;
						this.saveData = res.data[0];
						self.doc['isRecorded'] = res.data[0].isRecorded;
						self.doc['docInsUuid'] = res.data[0].docInsUuid;
						this.localCheckForm = docGoodsReg;
						if (flag === 'submit') {
							if (self.signImgList.length > 0) {
								this.$u.loading('数据提交中...');
								officeService.submitLocalCheck(bean, docUuid, titemUuid, id, type).then(res => {
									this.$u.hideLoading();
									this.saveBehaviorLog(1, this.caseParam, this.doc);
									if (res.success) {
										// 返回列表
										this.$u.toast(res.msg);
										self.backPrev({
											paramKey: "offiList",
											param: {
												caseUuid: bizUuid,
												caseCode: caseCode,
												caseType: caseType,
											},
										});
									} else {
										this.$u.toast(res.msg);
									}
								})
							} else {
								this.$modal.confirm('当事人未签名，是否继续提交?', () => {
									// this.$u.loading('数据提交中...');
									this.$u.loading('数据提交中...');
									officeService.submitLocalCheck(bean, docUuid, titemUuid, id, type).then(res => {
										this.$u.hideLoading();
										this.saveBehaviorLog(1, this.caseParam, this.doc);
										if (res.success) {
											// 返回列表
											this.$u.toast(res.msg);
											self.backPrev({
												paramKey: "offiList",
												param: {
													caseUuid: bizUuid,
													caseCode: caseCode,
													caseType: caseType,
												},
											});
										} else {
											this.$u.toast(res.msg);
										}
									})
								}, )
							}
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
						}
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
			// 添加承办人事件
			addPerson() {
				this.psParam = {
					min: 2,
					max: 2,
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				this.personList = [...e, ];
				let tIds = [];
				let tNames = [];
				this.personList.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName + "(" + el.leCertNo + ")");
				});
				this.localCheckForm['undertakerUuids'] = tIds.join(",");
				this.localCheckForm['undertaker'] = tNames.join(",");
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
						console.log('表单验证通过');
					} else {
						basicValid = false;
						console.log('表单验证失败');
					}
				});
				return basicValid;
			},
		},
	}
</script>
<style lang="scss" scoped>
	@import "../case_common.scss";

	/deep/ .main-content .u-cell {
		padding-left: 0px;
	}

	.check-content {
		padding-left: 15px;
		line-height: 28px;
	}

	.input-text {
		display: inline-flex;
		width: auto;
		text-align: center !important;
		flex: none;

		/deep/ .uni-input-input {
			border-bottom: 1px solid #999;
		}
	}

	/deep/.u-checkbox__label {
		font-size: 14px;
	}

	/deep/.uni-textarea-wrapper {
		line-height: 30px;
	}

	/deep/.u-td {
		white-space: nowrap;
		overflow: hidden;
	}
</style>
